/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

window.chsmsgid = false;

$(function() {
    // 加载已发列表
    loadSendList();
});

/**
 * 加载已发列表
 * @returns {undefined}
 */
function loadSendList() {
    wpLoading();
    $.post(shoproot + '?/WdminAjax/ajaxGetGroupSent/', {
        page: 1
    }, function(Res) {
        $('#card6-subtab2').html(Res);
        Loading.finish();
    });
}

function c6tab4onload() {
    __resize__();
    $('#cos-cent').css('margin-top',$('#cos-cent').parent().height() / 2);
    wpLoading();
    $.post(shoproot + '?/WdminAjax/ajaxGetGmessList2/', {
        page: 1
    }, function(Res) {
        $('#cos-left').html(Res);
        $('.gsend-chosbtn').click(function(){
            window.chsmsgid = $(this).attr('data-msgid');
            $('.js_appmsg_item.chois').removeClass('chois');
            $('#gsend-item' + chsmsgid).find('.js_appmsg_item').addClass('chois');
        });
        $('#gmess-send-btn1').unbind('click').click(function(){
            if(window.chsmsgid !== false){
                // 取值
                var title = $('.js_appmsg_item.chois').find('.gmessTitle').val();
                var descs = $('.js_appmsg_item.chois').find('.gmessDesc').val();
                var catimg = $('.js_appmsg_item.chois').find('.gmessCat').val();
                var Uri = $('.js_appmsg_item.chois').find('.gmessURI').val();
                // 走你
                gmessSend(Uri, title, descs, catimg, window.chsmsgid);
                $('#gmess-send-btn1').hide();
            } else {
                Alert('请在左侧选择图文素材');
            }
        });
        Loading.finish();
    });
}

/**
 * 获取图文列表
 * @returns {undefined}
 */
function loadGmessList() {
    wpLoading();
    $.post(shoproot + '?/WdminAjax/ajaxGetGmessList/', {
        page: 1
    }, function(Res) {
        $('#card6-subtab3').html(Res);
        $('.gmessDelBtn').click(function() {
            GmessDel($(this).attr('data-msgid'));
        });
        $('.gmessEditBtn').click(function() {
            GmessEdit($(this).attr('data-msgid'));
        });
        Loading.finish();
    });
}

function c6tab1onload() {
    $('#gs-form-title').unbind('keyup').keyup(function() {
        $('.appmsg_title > a').html($(this).val());
    });
    $('#gs-form-desc').unbind('keyup').keyup(function() {
        $('.appmsg_desc').html($(this).val());
    });
    ue = UE.getEditor('ueditor', {
        autoHeight: false
    });
    ue.ready(function() {
        ue.setHeight(document.documentElement.clientHeight - groupSendHeight);
        ueloaded = true;
    });
    
    // 素材保存按钮[图片已上传]
    $('#gmess-save-btn').unbind('click').click(function() {
        createGroupSendPage($('#gs-form-title').val(), ue.getContent(), $('#gs-form-desc').val(), window.gmessCatimg, true, window.gmessMsgId, GmessSaveCallBack);
    });

    // 按钮绑定
    var upBtn = window.gmessCatimg ? $("#gmess-save-btn").get(0) : $("#gmess-send-btn").get(0);
    
    window.isGmessCreate = window.gmessCatimg ? false : true;

    var params = {
        fileInput: $("#fileImage")[0],
        dragDrop: $("#fileDragArea").get(0),
        upButton: upBtn,
        url: $("#uploadForm").attr("action"),
        filter: function(files) {
            var arrFiles = [];
            for (var i = 0, file; file = files[i]; i++) {
                if (file.type.indexOf("image") == 0) {
                    if (file.size >= 512000) {
                        Alert('您这张"' + file.name + '"图片大小过大，应小于500k');
                    } else {
                        arrFiles.push(file);
                    }
                } else {
                    Alert('文件"' + file.name + '"不是图片。');
                }
            }
            return arrFiles;
        },
        onSelect: function(files) {
            var src = '', i = 0;
            var funAppendImage = function() {
                file = files[i];
                if (file) {
                    var reader = new FileReader()
                    reader.onload = function(e) {
                        src = e.target.result;
                        i++;
                        funAppendImage();
                    }
                    reader.readAsDataURL(file);
                } else {
                    window.groupImageURI = false;
                    $('.appmsg_thumb.default').hide();
                    $('#appmsimg-preview').attr('src', src).show();
                    if (src) {
                        $("#gmess-send-btn,#gmess-preview-btn").show();
                    } else {
                        //提交按钮隐藏
                        $("#gmess-send-btn,#gmess-preview-btn").hide();
                    }
                }
            };
            funAppendImage();
        },
        onDelete: function(file) {
            ZXXFILE.funDeleteFile(file.index);
        },
        onDragOver: function() {
            $(this).addClass("upload_drag_hover");
        },
        onDragLeave: function() {
            $(this).removeClass("upload_drag_hover");
        },
        onProgress: function(file, loaded, total) {

        },
        onSuccess: function(file, response) {
            var res = response.toJson();
            window.groupImageURI = res.imagepath;
            window.gmessCatimg = res.imagepath;
            if ($('#gs-form-title').val() !== '' && ue.getContent() !== '') {
                if (window.gmessCatimg && !isGmessCreate) {
                    // 保存
                    createGroupSendPage($('#gs-form-title').val(), ue.getContent(), $('#gs-form-desc').val(), window.gmessCatimg, true, window.gmessMsgId, GmessSaveCallBack);
                } else {
                    // 群发
                    createGroupSendPage($('#gs-form-title').val(), ue.getContent(), $('#gs-form-desc').val(), groupImageURI);
                }
            }
        },
        onFailure: function(file) {

        },
        onComplete: function() {

        }
    };
    ZXXFILE = $.extend(ZXXFILE, params);
    ZXXFILE.init();
}

/**
 * 消息群发 -> 图文素材
 * @returns {undefined}
 */
function c6tab3onload() {
    // 加载素材列表
    loadGmessList();
}

/**
 * 删除群发素材
 * @param {type} msgid
 * @returns {undefined}
 */
function GmessDel(msgid) {
    if (confirm('要删除这个素材吗？和这个素材相关的文章将失效')) {
        $.post('?/Gmess/ajaxDelByMsgId', {msgid: msgid}, function(r) {
            r = r.toJson();
            if (r.status > 0) {
                $('#gmessItem-' + msgid).fadeOut();
                loadGmessList();
            } else {
                Alert('删除失败');
            }
        });
    }
}

/**
 * 编辑群发素材
 * @param {type} msgid
 * @returns {undefined}
 */
function GmessEdit(msgid) {
    wpLoading();
    $.get('?/Gmess/ajaxGetGmess/id=' + msgid, function(r) {
        r = r.toJson();
        ue.ready(function() {
            ue.setContent(r.content);
            $('#_gmess_send').hide();
            $('#_gmess_edit').show();
            $('i.appmsg_thumb').hide();
            $('.appmsg_desc').html(r.desc);
            $('#appmsimg-preview').attr('src', r.catimg).show();
            $('.appmsg_title > a').html(r.title);
            $('#gs-form-title').val(r.title);
            $('#gs-form-desc').val(r.desc);
            window.gmessCatimg = r.catimg;
            window.gmessMsgId = msgid;
            subTabSwitch(1);
        });
        // 返回按钮
        $('#gmess-return-btn').click(__GmessEditFinish);
        Loading.finish();
    });
}

function __GmessEditFinish() {
    window.gmessCatimg = null;
    window.gmessMsgId = null;
    $('.appmsg_title > a').html('标题');
    $('.appmsg_desc').html('');
    $('#appmsimg-preview').attr('src', '').hide();
    $('i.appmsg_thumb').show();
    $('#uploadForm')[0].reset();
    $('#_gmess_send').show();
    $('#_gmess_edit').hide();
    ue.setContent('');
    subTabSwitch(3);
}

/**
 * 
 * @param {type} title
 * @param {type} content
 * @param {type} desc
 * @param {type} catimg
 * @returns {undefined}
 */
function createGroupSendPage(title, content, desc, catimg, update, msgid, _callback) {
    _callback = _callback || false;
    update = update || false;
    if (update) {
        /**
         * [HttpPost]
         * 素材保存
         */
        $.post('?/WdminAjax/alterGmessPage/isUpdate=1', {
            title: title,
            content: content,
            desc: desc,
            catimg: catimg,
            msgid: msgid
        }, function(res) {
            res = res.toJson();
            if (_callback !== false) {
                _callback(res.status > 0);
            }
        });
    } else {
        /**
         * [HttpPost]
         * 素材群发
         */
        $.post('?/WdminAjax/alterGmessPage/', {
            title: title,
            content: content,
            desc: desc,
            catimg: catimg
        }, function(res) {
            res = res.toJson();
            if (parseInt(res.status) === 1) {
                subTabSwitch(3);
            } else {
                Alert('系统错误！');
            }
        });
    }
}

function GmessSaveCallBack(su) {
    if (su) {
        // todo
        Alert('修改成功');
        __GmessEditFinish();
    } else {
        // 什么都没改动或者改动失败
    }
}